import os, time, sys
from configparser import ConfigParser
import selenium, datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import xlrd

local_dir = os.path.dirname(os.path.realpath(sys.argv[0]))

browser=None

try:
    cfg = ConfigParser()
    cfg.read('config.ini')
    chrome_path = cfg.get("env","chromepath")
    if chrome_path:
        chromeOptions = webdriver.ChromeOptions()
        chromeOptions.binary_location = str(chrome_path)
        browser = webdriver.Chrome(os.path.join(local_dir, "chromedriver.exe"), options=chromeOptions)
    else:
        browser = webdriver.Chrome(os.path.join(local_dir, "chromedriver.exe"))
except Exception:
    browser = webdriver.Chrome(os.path.join(local_dir, "chromedriver.exe"))

def check_env():
    try:
        cfg = ConfigParser()
        cfg.read('config.ini')
        return (
            cfg.get("oa","host"),
            cfg.get("user", "username"),
            cfg.get("user","password")
        )
    except Exception:
        print("无法读取配置文件, 请打开config.ini.example, 填入用户名密码, 将该文件保存为config.ini, 然后重新运行本程序.")

def read_excel():
    wb = xlrd.open_workbook(os.path.join(local_dir, "1.xlsx"))
    table = wb.sheets()[1]
    return table


def fuck_meal_rbs(host, username, password):
    cfg = ConfigParser()
    cfg.read('config.ini')
    year = cfg.get("env","year")
    ticketurl=cfg.get("oa","ticketurl")
    browser.get(host)
    browser.maximize_window()
    time.sleep(2)
    browser.find_element_by_css_selector('#loginid').send_keys(username)
    browser.find_element_by_css_selector('#userpassword').send_keys(password)
    browser.find_element_by_css_selector('#submit').click()
    time.sleep(5)
    if ticketurl:
        print("检测到你的配置文件中有ticketurl, 操作现有流程, 注意看清楚现在流程有多少行, 并填好startline")
        browser.get(ticketurl)
    else:
        print("未检测到你的配置文件中有ticketurl, 咱整个新流程")
        browser.get(f"{host}wui/index.html#/main/workflow/add?menuIds=1,12&menuPathIds=1,12&_key=2pc0s0")
        time.sleep(5)
        browser.find_element_by_css_selector('a[title="餐费报销"]').click()
    time.sleep(2)
    browser.switch_to.window(browser.window_handles[-1]) # 必须切换
    table = read_excel()

    startline = cfg.get("oa","startline")
    if startline:
        startline = int(startline)
        cnt = startline
        print(f"已读取startline, 将从第{startline}行开始")
    else:
        startline = 0
        cnt = 0
        print(f"没读到startline, 将从第0行开始, 想跳行的话, cfg.ini字段下, 给个startline的值.")
    total_money = 0
    for row in range(startline+2, table.nrows):
        print(f"开始处理第{row}/{table.nrows}行...")
        line = table.row_values(row)
        if str(line[1]).replace(" ","") == "":
            browser.find_element_by_css_selector(
                f'div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 > div > span:nth-child(2) > button').click()
            time.sleep(2)
            break

        total_money += line[4]
        next_line = 0 if not table.row_values(row + 1)[4] else table.row_values(row + 1)[4]
        total_money2 = total_money + next_line

        try:
            browser.find_elements_by_css_selector('i#addbutton3')[-1].click()
        except selenium.common.exceptions.WebDriverException:
            browser.find_elements_by_css_selector('i#addbutton3')[0].click()

        time.sleep(0.5)
        try:
            browser.find_element_by_css_selector(f'tr[data-rowindex="{cnt}"]>td.etype_3 i.anticon-search').click()
            time.sleep(5)
            browser.find_elements_by_css_selector('input.ant-input.undefined')[-1].send_keys(
                str(line[6]).replace(" ", ""))
            time.sleep(3)
            browser.find_elements_by_css_selector('input.ant-input.undefined')[-1].send_keys(Keys.ENTER)  # 需要按回车
            time.sleep(3)
            browser.find_elements_by_css_selector('div.resource-content.breakall')[0].click()
            time.sleep(0.5)
        except Exception as e:
            com_log_txt(str(int(line[1]))+ str(line[6]))

        try:
            if type(line[2]) == float and float(line[2]) > 10000 and float(line[2]) < 100000:
                dt = xlrd.xldate.xldate_as_datetime(table.cell(row, 2).value, 0)
                date = dt.strftime("%Y-%m-%d")
            elif type(line[2]) == float and float(line[2]) > 100000:
                date = str(line[2]).split(".")[0]
                date = date[:4] + "-" + date[4:6] + "-" + date[6:]
            elif type(line[2]) == float and float(line[2]) < 15:
                date = str(line[2])
                date = f"{year}-" + date.split(".")[0] + '-' + date.split(".")[1]
            js = f'''$('tr[data-rowindex="{cnt}"] span.ant-calendar-picker span.text').html("{date}")'''
            browser.execute_script(js)
            js = f'''$('input#field7671_{cnt}').val("{date}")'''
            browser.execute_script(js)
            time.sleep(2)
        except Exception as e:
            com_log_txt(str(int(line[1])) + str(line[2]))

        try:
            browser.find_element_by_css_selector(f'.field7672_{cnt}_swapDiv > div').click()
            time.sleep(1)
            if line[5].strip() == "早餐":
                browser.find_elements_by_css_selector(f'li[title="早餐"]')[-1].click()
                time.sleep(0.5)
            elif line[5].strip() == "午餐":
                browser.find_elements_by_css_selector(f'li[title="午餐"]')[-1].click()
                time.sleep(0.5)
            elif line[5].strip() == "晚餐":
                browser.find_elements_by_css_selector(f'li[title="晚餐"]')[-1].click()
                time.sleep(0.5)
        except Exception as e:
            com_log_txt(str(int(line[1])) + str(line[5]))

        try:
            browser.find_elements_by_css_selector(f'tr[data-rowindex="{cnt}"]>td.etype_3.detail_4_3_5 input')[
                -1].send_keys(
                "1" if not str(line[3]) else str(line[3]).split(".")[0]
            )
            time.sleep(0.5)
        except Exception as e:
            com_log_txt(str(int(line[1])) + str(line[3]))

        try:
            browser.find_elements_by_css_selector(f'tr[data-rowindex="{cnt}"]>td.etype_3.detail_4_3_6 input')[
                -1].send_keys(
                "" if int(line[4]) >= 5000 else str(line[4])
            )
            time.sleep(0.5)
        except Exception as e:
            com_log_txt(str(int(line[1])) + str(line[4]))

        try:
            browser.find_elements_by_css_selector(f'tr[data-rowindex="{cnt}"]>td.etype_3.detail_4_3_7 input')[
                -1].send_keys(
                str(line[9])
            )
        except Exception as e:
            com_log_txt(str(int(line[1])) + str(line[9]))

        if total_money < 5000 and total_money2 > 5000:
            cnt = 0
            browser.find_element_by_css_selector(f'div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 > div > span:nth-child(2) > button').click()
            time.sleep(5)
            browser.close()
            total_money = 0
            browser.switch_to.window(browser.window_handles[0])
            time.sleep(0.5)
            browser.find_element_by_css_selector('a[title="餐费报销"]').click()
            time.sleep(2)
            browser.switch_to.window(browser.window_handles[1])  # 必须切换
        elif total_money < 5000 and total_money2 < 5000:
            cnt = cnt + 1

    browser.close()
    browser.quit()

# 写日志
def com_log_txt(message):
    url = "D:\\oa_log\\"
    shotname = datetime.datetime.now().strftime('%Y-%m-%d')
    extension = ".txt"
    filename = os.path.join(url, shotname + extension)
    with open(filename, "a") as f:
        time_str = datetime.datetime.now()
        star_str = "At" + str(time_str) + "......:\n"
        f.write(star_str)
        f.writelines(message + "\n")

def hello():
    input('''
    把Excel中的信息倒到OA里, 需要三步:
    1. 右键目录内config.ini.example, 填上OA用户名密码, 这个文件另存为config.ini
    2. 把excel拷贝到目录内, 重命名成1.xlsx, 也就是替换掉目前目录中的1.xlsx
    3. 准备好上面两步后, 按回车键开始
    ''')

if __name__ == '__main__':
    hello()
    host, username, password = check_env()
    fuck_meal_rbs(host, username, password)
    input("整完了, 程序整的匆忙, 请务必检查一遍, 尤其是什么重名的, 金额不规范的, 然后把其他项目填好, 提交或者保存完流程, 按回车键结束.")
    input("确定整完了哈, 再按一次回车键程序和浏览器都退出了嗷.")
